<script>
	import { goto } from '$app/navigation';
	import { userSignIn, userSignUp } from '$lib/apis/auths';
	import Spinner from '$lib/components/common/Spinner.svelte';
	import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
	import { WEBUI_NAME, config, user } from '$lib/stores';
	import { onMount, getContext } from 'svelte';
	import { toast } from 'svelte-sonner';
	import { generateInitialsImage, canvasPixelTest } from '$lib/utils';
	import yunhanLogo from '../../public/image/logo.png';
	import fuzzyImg from '../../public/image/fuzzy-cloud.png';
	import yunhanImg from '../../public/image/yunhan.png';
	import PasswordInput from '$lib/components/common/PasswordInput.svelte';

	const i18n = getContext('i18n');

	let loaded = false;
	let mode = 'signin';

	let name = '';
	let email = '';
	let password = '';
	// 工作单位
	let organization = '';
	// 姓名
	let fullName = '';
	// 手机号
	let phone = '';

	const setSessionUser = async (sessionUser) => {
		if (sessionUser) {
			console.log(sessionUser);
			toast.success($i18n.t(`You're now logged in.`));
			localStorage.token = sessionUser.token;
			await user.set(sessionUser);
			goto('/');
		}
	};

	const signInHandler = async () => {
		const sessionUser = await userSignIn(email, password).catch((error) => {
			toast.error(error);
			return null;
		});

		await setSessionUser(sessionUser);
	};

	const signUpHandler = async () => {
		const sessionUser = await userSignUp(
			name,
			email,
			password,
			organization,
			fullName,
			phone,
			generateInitialsImage(name)
		).catch((error) => {
			toast.error(error);
			return null;
		});

		await setSessionUser(sessionUser);
	};

	const submitHandler = async () => {
		if (mode === 'signin') {
			await signInHandler();
		} else {
			await signUpHandler();
		}
	};

	onMount(async () => {
		if ($user !== undefined) {
			await goto('/');
		}
		loaded = true;
		if ($config?.trusted_header_auth ?? false) {
			await signInHandler();
		}
	});
</script>

<svelte:head>
	<title>
		{`${$WEBUI_NAME}`}
	</title>
</svelte:head>

{#if loaded}
	<div class="fixed m-8 z-50">
		<div class="flex space-x-2">
			<div class=" self-center">
				<!-- <img src="{WEBUI_BASE_URL}/static/logo.png" class=" w-8" alt="logo" /> -->
				<img src={yunhanLogo} class="w-[min(100px,10vw)]" alt="logo" />
			</div>
		</div>
	</div>

	<div class=" min-h-screen w-full flex justify-center font-mona bg-auth">
		<!-- <div class="hidden lg:flex lg:flex-1 px-10 md:px-16 w-full bg-yellow-50 justify-center">
			<div class=" my-auto pb-16 text-left">
				<div>
					<div class=" font-bold text-yellow-600 text-4xl">
						Get up and running with <br />large language models, locally.
					</div>

					<div class="mt-2 text-yellow-600 text-xl">
						Run Llama 2, Code Llama, and other models. Customize and create your own.
					</div>
				</div>
			</div>
		</div> -->

		<div class="w-full sm:max-w-lg px-4 min-h-screen flex flex-col">
			{#if $config?.trusted_header_auth ?? false}
				<div class=" my-auto pb-10 w-full">
					<div
						class="flex items-center justify-center gap-3 text-xl sm:text-2xl text-center font-bold dark:text-gray-200"
					>
						<div>
							{$i18n.t('Signing in')}
							{$i18n.t('to')}
							{$WEBUI_NAME}
						</div>

						<div>
							<Spinner />
						</div>
					</div>
				</div>
			{:else}
				<div class="relative z-0 my-auto pb-10 w-full">
					<form
						class=" flex flex-col justify-center py-6 sm:py-16 px-6 sm:px-16 rounded-2xl"
						on:submit|preventDefault={() => {
							submitHandler();
						}}
					>
						<div class="relative text-xl sm:text-2xl font-bold text-center h-[20dvh] mb-[5dvh]">
							<!-- {mode === 'signin' ? $i18n.t('Sign in') : $i18n.t('Sign up')}
							{$i18n.t('to')}
							{$WEBUI_NAME} -->
							<img src={fuzzyImg} class="absolute top-0 left-0 -z-10" alt="logo" />
							<img
								src={yunhanImg}
								class="block m-auto max-h-full max-w-full object-contain"
								alt="云瀚智慧套件"
							/>
						</div>

						<!-- {#if mode === 'signup'}
							<div class=" mt-1 text-xs font-medium text-gray-500">
								ⓘ {$WEBUI_NAME}
								{$i18n.t(
									'does not make any external connections, and your data stays securely on your locally hosted server.'
								)}
							</div>
						{/if} -->

						<div class="flex flex-col mt-4">
							{#if mode === 'signup'}
								<div class="mb-4">
									<div class=" text-sm font-semibold text-left mb-1 text-white">
										{$i18n.t(/* 'Name' */ '用户名')}
									</div>
									<input
										bind:value={name}
										type="text"
										class="text-white bg-[rgba(54,58,72,0.5)] border-none outline-none px-4 py-2.5 rounded-md w-full text-sm"
										autocomplete="name"
										placeholder={$i18n.t(/*'Enter Your Full Name'*/ '请输入用户名')}
										required
									/>
								</div>

								<!-- <hr class=" my-3" /> -->
							{/if}

							<div class="mb-4">
								<div class=" text-sm font-semibold text-left mb-1 text-white">
									{$i18n.t(/* 'Email' */ '邮箱')}
								</div>
								<input
									bind:value={email}
									type="email"
									class="text-white bg-[rgba(54,58,72,0.5)] border-none outline-none px-4 py-2.5 rounded-md w-full text-sm"
									autocomplete="email"
									placeholder={$i18n.t(/* 'Enter Your Email' */ '请输入邮箱')}
									required
								/>
							</div>

							<div class={mode === 'signup' ? 'mb-4' : ''}>
								<div class=" text-sm font-semibold text-left mb-1 text-white">
									{$i18n.t('Password')}
								</div>
								<!-- <input
									bind:value={password}
									type="password"
									class=" bg-[rgba(54,58,72,0.5)] border-none px-4 py-2.5 rounded-md w-full text-sm"
									placeholder={$i18n.t('Enter Your Password')}
									autocomplete="current-password"
									required
									/> -->
								<PasswordInput
									bind:value={password}
									class="text-white bg-[rgba(54,58,72,0.5)] border-none outline-none px-4 py-2.5 rounded-md w-full text-sm"
									placeholder="请输入密码"
									autocomplete="current-password"
									required
								/>
							</div>

							{#if mode === 'signup'}
								<div class="mb-4">
									<div class=" text-sm font-semibold text-left mb-1 text-white">工作单位（非必填）</div>
									<input
										bind:value={organization}
										type="text"
										class="text-white bg-[rgba(54,58,72,0.5)] border-none outline-none px-4 py-2.5 rounded-md w-full text-sm"
										autocomplete="organization"
										placeholder="请输入工作单位"
									/>
								</div>
								<div class="mb-4">
									<div class=" text-sm font-semibold text-left mb-1 text-white">姓名（非必填）</div>
									<input
										bind:value={fullName}
										type="text"
										class="text-white bg-[rgba(54,58,72,0.5)] border-none outline-none px-4 py-2.5 rounded-md w-full text-sm"
										autocomplete="name"
										placeholder="请输入姓名"
									/>
								</div>
								<div>
									<div class=" text-sm font-semibold text-left mb-1 text-white">手机号（非必填）</div>
									<input
										bind:value={phone}
										type="tel"
										class="text-white bg-[rgba(54,58,72,0.5)] border-none outline-none px-4 py-2.5 rounded-md w-full text-sm"
										autocomplete="tel"
										placeholder="请输入手机号"
									/>
								</div>
							{/if}
						</div>

						<div class="mt-8">
							<button
								class=" bg-[#E95513] hover:bg-[#ff915d] w-full rounded-md text-white font-semibold text-sm py-3 transition"
								type="submit"
							>
								{mode === 'signin' ? $i18n.t('Sign in') : $i18n.t('Create Account')}
							</button>

							<div class=" mt-4 text-sm text-center text-white">
								{mode === 'signin'
									? $i18n.t(/* "Don't have an account?" */ '新用户')
									: $i18n.t(/* 'Already have an account?' */ '已有账号请')}

								<button
									class=" font-medium text-[rgba(233,85,19,1)]"
									type="button"
									on:click={() => {
										if (mode === 'signin') {
											mode = 'signup';
										} else {
											mode = 'signin';
										}
									}}
								>
									{mode === 'signin' ? $i18n.t('Sign up') : $i18n.t('Sign in')}
								</button>
							</div>
						</div>
					</form>
				</div>
			{/if}
		</div>
	</div>
{/if}

<style>
	.font-mona {
		font-family: 'Mona Sans';
	}

	.bg-auth {
		background-color: black;
		background-image: url(../../public/image/bg-auth.png), url(../../public/bg.png);
		background-position: center;
		background-repeat: no-repeat;
		background-size: cover;
		background-attachment: fixed;
	}
</style>
